<?php
/**
 * 上传图片
 *
 * @author xue
 */
namespace Card\Controller;
use Card\Controller\PublicController;
use Think\Image;

class UploadController extends PublicController {
    public function index(){
        $this->meta_title = '上传图片';
        $this->display('index');
    }
    /**
     * 上传图片
     */
    public function UploadImages(){
        $data = inputJson();
        // $data['phpsid'] = 'r3gkrukc7ttcbnheei97o81bc7';//上传照片墙时需要传输session_id,用来存储图片到用户的照片墙内

    	// var_dump($_FILES);exit;

    	/* 返回标准数据 */
        $return  = array('status' => 1, 'info' => '上传成功', 'data' => '');

        /* 调用文件上传组件上传文件 */
        $Picture = D('Picture');
        $pic_driver = C('PICTURE_UPLOAD_DRIVER');

        $info = $Picture->upload(
            $_FILES,
            C('PICTURE_UPLOAD'),
            C('PICTURE_UPLOAD_DRIVER'),
            C("UPLOAD_{$pic_driver}_CONFIG")
        ); //TODO:上传到远程服务器
        // var_dump($info);

        $path = C('PICTURE_UPLOAD');
        $img_path = 'http://'.$_SERVER['HTTP_HOST'].$info['file']['path'];
        // var_dump($img_path);exit;

        /* 记录图片信息 */
        if($info){
            $return['status'] = 1;
            $return['img_id'] = $info['file']['id'];
        	$return['path'] = $img_path; 
            // $return = array_merge($info['download'], $return);
        } else {
            $return['status'] = 0;
            $return['info']   = $Picture->getError();
        }
        //如果有session_id说明是上传照片墙,则把新的图片id存入云名片用户图片id内
        if(!empty($data['phpsid'])){
            $user_id = $this->get_userId($data['phpsid']);
            if($user_id === false){
                errorOutputJson('g'.__LINE__);
            }
            $res = D('CardId')->getCidInfo(array('user_id'=>$user_id),'img_id');
            if(empty($res['img_id'])){
                $cdata['img_id'] = $return['img_id'];
            }else{
                $cdata['img_id'] = $res['img_id'].','.$return['img_id'];
            }
            $condition = array('user_id'=>$user_id);
            $res = D('CardId')->saveCart($condition,$cdata);
            if($res === false){
                errorOutputJson('g'.__LINE__);
            }
        }

        /* 返回JSON数据 */
        $this->ajaxReturn($return);

    }

     /**
     * 上传base64图片(照片墙也包含在内)
     */
    public function base64UploadImages(){
        // $data = inputJson();

        //如果有session_id说明是上传照片墙,不能超过20张
        if(!empty($_POST['phpsid'])){
            $user_id = $this->get_userId($_POST['phpsid']);
            if($user_id === false){
                errorOutputJson('g'.__LINE__);
            }
            $res = D('CardId')->getCidInfo(array('user_id'=>$user_id),'img_id');
            if(!empty($res['img_id'])){
                $img_arr = explode(',', $res['img_id']);
                foreach ($img_arr as $k => $v) {
                    $i++;//照片总数
                }
                if($i >= 20){
                    $return['status'] = 0;
                    $return['info']   = '上传的照片不能超过20张';
                    $this->ajaxReturn($return);
                }

            }
        }

        $base64_image_content = $_POST['base64Img'];

        //匹配出图片的格式
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
            $type = $result[2];
            $new_file = C('PICTURE_UPLOAD')['rootPath'].date('Y-m-d',time())."/";
            
            if(!file_exists($new_file))
            {
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdir($new_file, 0700, true);
            }
            $new_file = $new_file.time().".{$type}";
            if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){
                //存数据库 路径:$new_file
                $data['path'] = $new_file;
                $data['create_time'] = time();
                $res = D('Picture')->add($data);
                if(!$res){
                    $return['status'] = 0;
                    $return['info']   = '上传失败';
                }else{
                    $img_path = 'http://'.$_SERVER['HTTP_HOST'].$data['path'];
                    $return['status'] = 1;
                    $return['img_id'] = $res;
                    $return['path'] = $img_path; 

                    //如果有session_id说明是上传照片墙,则把新的图片id存入云名片用户图片id内
                    if(!empty($_POST['phpsid'])){
                        //照片墙上传 生成缩略图
                        $image = new \Think\Image();
                        $image->open($data['path']);
                        //贺卡中间的照片大小
                        $image->thumb(680, 970,\Think\Image::IMAGE_THUMB_CENTER)->save($data['path']);
                        //照片墙小图
                        $image->thumb(300, 300,\Think\Image::IMAGE_THUMB_CENTER)->save($data['path'].'.s.jpg');
                        $return['small_path'] = 'http://'.$_SERVER['HTTP_HOST'].$data['path'].'.s.jpg';

                        $user_id = $this->get_userId($_POST['phpsid']);
                        if($user_id === false){
                            errorOutputJson('g'.__LINE__);
                        }
                        $res = D('CardId')->getCidInfo(array('user_id'=>$user_id));
                        if(empty($res)){
                            //没有记录，增加记录
                            $cdata['img_id'] = $return['img_id'];
                            $cdata['user_id'] = $user_id;
                            $res = D('CardId')->add($cdata);
                            if(!$res){
                                errorOutputJson('g'.__LINE__);
                            }else{
                                $this->ajaxReturn($return);
                            }
                        }else{
                            $res = D('CardId')->getCidInfo(array('user_id'=>$user_id),'img_id');
                            if(empty($res['img_id'])){
                                $cdata['img_id'] = $return['img_id'];
                            }else{
                                $cdata['img_id'] = $return['img_id'].','.$res['img_id'];
                            }
                            $condition = array('user_id'=>$user_id);
                            $res = D('CardId')->saveCart($condition,$cdata);
                            if($res === false){
                                errorOutputJson('g'.__LINE__);
                            }
                        }
                        
                    }
                    
                }

                $this->ajaxReturn($return);
            }else{
                $return['status'] = 0;
                $return['info']   = '上传失败';
                $this->ajaxReturn($return);
            }
        }

    }
}